package com.qys.livesMall.shop.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.qys.livesMall.app.user.mapper.H2AppUserMapper;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.app.user.utils.TencentCloudIm;
import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.common.constants.Constants;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.DateUtils;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.finance.enums.AccountBusinessTypeEnum;
import com.qys.livesMall.finance.model.dto.FinancePayDTO;
import com.qys.livesMall.finance.service.FinanceBusinessService;
import com.qys.livesMall.finance.util.BusinessNoUtil;
import com.qys.livesMall.framework.utils.SnowflakeGenerator;
import com.qys.livesMall.open.enums.PushMessageTypeEnum;
import com.qys.livesMall.open.modal.dto.app.PushUserDeviceContentDTO;
import com.qys.livesMall.open.modal.dto.mail.PushAllDeviceDTO;
import com.qys.livesMall.open.modal.dto.mail.PushTitleDTO;
import com.qys.livesMall.open.modal.dto.mail.PushUserDeviceDTO;
import com.qys.livesMall.open.service.PushUserDeviceService;
import com.qys.livesMall.open.uniapp.Result;
import com.qys.livesMall.product.entity.H2ProductCategory;
import com.qys.livesMall.product.service.H2ProductCategoryService;
import com.qys.livesMall.shop.constants.*;
import com.qys.livesMall.shop.enums.ShopBusinessTypeEnum;
import com.qys.livesMall.shop.enums.ShopEventTypeEnum;
import com.qys.livesMall.shop.enums.ShopMessageEnum;
import com.qys.livesMall.shop.event.ShopEvent;
import com.qys.livesMall.shop.event.shop.pojo.ShopOrderPojo;
import com.qys.livesMall.shop.mapper.ShopGoodsSkuStocksMapper;
import com.qys.livesMall.shop.mapper.ShopOrderInfoMapper;
import com.qys.livesMall.shop.modal.entity.*;
import com.qys.livesMall.shop.open.anchor.service.AnchorServer;
import com.qys.livesMall.shop.service.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gmx
 * @since 2023-06-19
 */
@Service
@Slf4j
public class ShopOrderInfoServiceImpl extends ServiceImpl<ShopOrderInfoMapper, ShopOrderInfo> implements ShopOrderInfoService {

    @Resource
    private SeckillOrderService seckillOrderService;
    @Resource
    private ShopOrderIdeaService ideaService;
    @Resource
    FinanceBusinessService financeBusinessService;
    @Resource
    H2ShopBaseService shopBaseService;
    @Resource
    private ShopOrderInfoService orderInfoService;
    @Resource
    private ShopOrderSkuService orderSkuService;
    @Resource
    private ShopGoodsSkuStocksMapper skuStocksMapper;
    @Resource
    private ShopGoodsInfoService infoService;
    @Resource
    private ShopGoodsSkuService skuService;
    @Resource
    private H2ProductCategoryService categoryService;
    @Resource
    private ShopGoodsSkuStocksService skuStocksService;
    @Resource
    private PushUserDeviceService pushUserDeviceService;
    @Resource
    private ShopOrderMessageService messageService;
    @Resource
    private H2AppUserMapper userMapper;
    @Resource
    private ShopOrderSettlementService shopOrderSettlementService;
    @Resource
    private RedisCache redisCache;

    @Autowired
    private ShopGoodsInfoService shopGoodsInfoService;
    @Autowired
    private ShopGoodsSkuService shopGoodsSkuService;
    @Resource
    private ApplicationContext applicationContext;
    @Resource
    private AnchorServer anchorServer;
    @Resource
    private TencentCloudIm tencentCloudIm;

    @Autowired
    private ShopOrderStatusManager shopOrderStatusManager;

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public R<ShopOrder> add(ShopOrderInfo order,List<ShopOrderSku> orderSkus,Integer source) {
        order.setPayStatus(PayStatus.NONPAYMENT);
        order.setIsDelete(Constants.YesNo.NO);
        order.setCreateTime(System.currentTimeMillis());
        order.setUpdateTime(order.getCreateTime());

        int totalNum =0;
        BigDecimal payMoney = new BigDecimal(0.0000);
        List<Long> skuIds= orderSkus.stream().map(ShopOrderSku::getSkuId).collect(Collectors.toList());
        BigDecimal totalPostage= shopGoodsSkuService.getPostage(skuIds);

        for(ShopOrderSku orderSku: orderSkus){
            long snowID = SnowflakeGenerator.generateSnowflakeID(1L);
            orderSku.setId(snowID);
            orderSku.setOrderId(order.getId());
            orderSku.setUserId(order.getUserId());

            ShopGoodsSku goodsSku=skuService.getById(orderSku.getSkuId());
            orderSku.setName(goodsSku.getSkuName());
            ShopGoodsInfo goodsInfo = infoService.getById(goodsSku.getShopGoodsId());
            orderSku.setImage(goodsInfo.getImage());
            orderSku.setShopId(goodsInfo.getShopId());
            if(!goodsInfo.isStatus()){
                throw new QysException(MessageUtils.message("shop.goods.off",goodsInfo.getGoodsName()));
            }
            //店铺信息
            H2ShopBase shopBase = shopBaseService.queryById(goodsInfo.getShopId());
            orderSku.setShopName(shopBase.getShopName());
            //分类-邮费
            H2ProductCategory cate = categoryService.getById(goodsInfo.getCategoryTwoId());
            BigDecimal postage = new BigDecimal(0.0000);
            if (cate!=null){
                postage=cate.getPostage();

            }
            orderSku.setPostage(postage);
            orderSku.setCategoryId(cate!=null?cate.getId():null);

            //获得库存
            LambdaQueryWrapper<ShopGoodsSkuStocks> stocksWrapper = new LambdaQueryWrapper<>();
            stocksWrapper.eq(ShopGoodsSkuStocks::getSkuId,goodsSku.getId());
            stocksWrapper.eq(ShopGoodsSkuStocks::getState,false);
            stocksWrapper.ne(ShopGoodsSkuStocks::getNum, 0);
            stocksWrapper.orderByAsc(ShopGoodsSkuStocks::getCreateTime);
            List<ShopGoodsSkuStocks> stocks = skuStocksService.list(stocksWrapper);
            if (ObjectUtils.isEmpty(stocks)) throw new QysException(MessageUtils.message("understock"));
            ShopGoodsSkuStocks minStocks = stocks.stream().min(Comparator.comparing(ShopGoodsSkuStocks::getCreateTime)).orElse(null);
            int i = skuStocksMapper.decount(minStocks.getId(),orderSku.getNum());
            if (i<1)throw new QysException(MessageUtils.message("understock"));
            //不是秒杀，价格重新计算
            if(!Objects.equals(source, ShopConstant.OrderSource.SECKILL)){
                BigDecimal price = minStocks.getPrice();
                orderSku.setPrice(price);
                BigDecimal money = price.multiply(new BigDecimal(orderSku.getNum()));
                orderSku.setMoney(money);
            }
            orderSku.setStocksId(minStocks.getId());
            orderSku.setCostPrice(minStocks.getCostPrice());

            orderSku.setSkuOrderId(ShopBusinessTypeEnum.USER_ORDER.getPrefix() +snowID);
            String userSysType = userMapper.getUserSysType(order.getUserId());
            orderSku.setVirtualUser(userSysType);
            orderSku.setCreateTime(LocalDateTime.now());
            orderSku.setOrderStatus(OrderStatus.WAIT_PAY);
            orderSku.setReview(Constants.YesNo.NO);
            orderSku.setCostPay(Constants.YesNoInt.YES);
            orderSku.setCostPayType(PayMethod.CostPayType.PURCHASE);
            if(Objects.equals(minStocks.getPayType(), Constants.YesNo.NO)){
                orderSku.setCostPay(Constants.YesNoInt.NO);
                orderSku.setCostPayType(null);
            }
            orderSkuService.save(orderSku);
            //统计数据
            totalNum+=orderSku.getNum();
            payMoney=payMoney.add(orderSku.getMoney());
        }
        order.setTotalNum(totalNum);
        order.setMoneys(payMoney);
        order.setTotalPostage(totalPostage);
        if (totalPostage==null){
            order.setTotalPostage(new BigDecimal("0"));
        }
        order.setOrderNo(BusinessNoUtil.get(AccountBusinessTypeEnum.USER_ORDER));
        order.setOrderStatus(OrderStatus.WAIT_PAY);
        if(!save(order)) throw new QysException(MessageUtils.message("system.error.order"));
        ShopOrder shopOrder = new ShopOrder();
        shopOrder.setOrderInfo(order);
        shopOrder.setOrderSkus(orderSkus);
        return R.ok(shopOrder);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public R cancel(ShopOrderIdea idea) {
        ShopOrderInfo orderInfo = super.getById(idea.getOrderId());
        if (ObjectUtils.isEmpty(orderInfo))return R.fail(MessageUtils.message("system.error.order"));
        LambdaQueryWrapper<ShopOrderSku> orderSkuLambdaQueryWrapper= new LambdaQueryWrapper<>();
        orderSkuLambdaQueryWrapper.eq(ShopOrderSku::getOrderId,idea.getOrderId());
        List<ShopOrderSku> orderSkus = orderSkuService.list(orderSkuLambdaQueryWrapper);
        if (orderSkus.size()==0)return R.fail(MessageUtils.message("system.error.order"));
        for (ShopOrderSku orderSku : orderSkus) {
            orderSku.setOrderStatus(OrderStatus.CANCELED);
            orderSkuService.updateById(orderSku);
            Long stocksId = orderSku.getStocksId();
            Integer num = orderSku.getNum();
            int i = skuStocksMapper.decount(stocksId, -num);
            if (i<1)throw new QysException(MessageUtils.message("system.error.order"));
        }
        orderInfo.setOrderStatus(OrderStatus.CANCELED);
        if(!super.updateById(orderInfo)) throw new QysException(MessageUtils.message("system.error.order"));
        idea.setCreateTime(System.currentTimeMillis());
        ideaService.saveOrUpdate(idea);
        return R.ok();
    }

    @Override
    public R delete(ShopOrderIdea idea)  {
        return R.ok(super.removeById(idea.getOrderId()));
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public R operation(Long id) {
        long now = System.currentTimeMillis();
        ShopOrderSku orderSku = orderSkuService.getById(id);
        if(ObjectUtils.isEmpty(orderSku))return R.fail(MessageUtils.message("system.error.order"));
        if (!(orderSku.getOrderStatus().equals(OrderStatus.SHIPPED)))return R.fail(MessageUtils.message("order.not.shipped"));
        orderSku.setOrderStatus(OrderStatus.RECEIVED);
        orderSku.setEndTime(now);
        if(!orderSkuService.updateById(orderSku)) throw new QysException(MessageUtils.message("system.error.order"));
        //更新主订单状态
        ShopOrderInfo orderInfo = getById(orderSku.getOrderId());
        List<ShopOrderSku> orderSkus = orderSkuService.getStatusByOrderId(orderInfo.getId());
        orderInfo.setOrderStatus(shopOrderStatusManager.getMainOrderStatus(orderSkus));
        if(!super.updateById(orderInfo)) throw new QysException(MessageUtils.message("system.error.order"));

        return R.ok();
    }

    @Override
    public Integer getOrderNum(Long shopId, LocalDateTime startTime, LocalDateTime endTime) {
        Integer num=baseMapper.getOrderNum(shopId,startTime,endTime);
        return num==null?0:num;
    }

    @Override
    public Integer getGoodsNum(Long shopId, LocalDateTime startTime, LocalDateTime endTime) {
        Integer num=baseMapper.getGoodsNum(shopId,startTime,endTime);
        return num==null?0:num;
    }

    @Override
    public Long getWaitShipNum(Long shopId) {
        LambdaQueryWrapper<ShopOrderSku> wq=new LambdaQueryWrapper<>() ;
        wq.eq(ShopOrderSku::getShopId,shopId);
        wq.eq(ShopOrderSku::getOrderStatus,OrderStatus.UNSHIPPED);
        return orderSkuService.count(wq);
    }

    @Override
    public Long getWaitReturnNum(Long shopId) {
        LambdaQueryWrapper<ShopOrderSku> wq=new LambdaQueryWrapper<>() ;
        wq.eq(ShopOrderSku::getShopId,shopId);
        wq.in(ShopOrderSku::getOrderStatus,OrderStatus.RETURN_APPLIED,OrderStatus.RETURN_CONFIRMED);
        return orderSkuService.count(wq);
    }

    @Override
    public void shipped(Long orderSkuId) {
        ShopOrderSku orderSku = orderSkuService.getById(orderSkuId);
        if (orderSku==null){
        throw new QysException(ShopMessageEnum.SHOP_NOT_FIND_ORDER);
        }
        long now = System.currentTimeMillis();

        if (Objects.equals(orderSku.getOrderStatus(), OrderStatus.SHIPPED)){
            return;
        }
        if (!Objects.equals(orderSku.getOrderStatus(), OrderStatus.UNSHIPPED)) {
            throw new QysException(ShopMessageEnum.SHOP_ORDER_STATUS_EXCEPTION);
        }
        if (Objects.equals(orderSku.getCostPay(), Constants.YesNoInt.NO)){
            throw new QysException(ShopMessageEnum.SHOP_ORDER_NO_PAYMENT_FOR_GOODS);
        }
        orderSku.setConsignTime(now);
        orderSku.setOrderStatus(OrderStatus.SHIPPED);
        if (!orderSkuService.updateById(orderSku))
            throw new QysException(MessageUtils.message("system.error.order"));

        try {
            ShopOrderInfo orderInfo = orderInfoService.getById(orderSku.getOrderId());
            List<ShopOrderSku> allOrderSkus = orderSkuService.getStatusByOrderId(orderInfo.getId());
            orderInfo.setOrderStatus(shopOrderStatusManager.getMainOrderStatus(allOrderSkus));
            orderInfo.setConsignTime(now);
            if (!orderInfoService.updateById(orderInfo))
                throw new QysException(MessageUtils.message("system.error.order"));
        } catch (QysException e) {
            R.fail(e.getMessage());
        }
    }

    @Override
    public List<ShopOrderInfo> getOutTimeShipped(long start, long end) {
        LambdaQueryWrapper<ShopOrderInfo> wq=new LambdaQueryWrapper<>() ;
        wq.eq(ShopOrderInfo::getOrderStatus,OrderStatus.UNSHIPPED);
        wq.eq(ShopOrderInfo::getIsDelete, Constants.YesNo.NO);
        wq.gt(ShopOrderInfo::getPayTime, start);
        wq.le(ShopOrderInfo::getPayTime, end);
        return orderInfoService.list(wq);
    }

    @Override
    public List<ShopOrderInfo> getOrderYesterday() {
        return baseMapper.getOrderYesterday();
    }


    @Override
    @Transactional(rollbackFor = {Exception.class})
    public R pay(Long orderId) {
        synchronized (orderId) {
            ShopOrderInfo order = getById(orderId);
            if (order == null) {
                throw new QysException(MessageUtils.message("shop.order.null"));
            }
            if (!Objects.equals(order.getOrderStatus(),OrderStatus.WAIT_PAY)) {
                throw new QysException(MessageUtils.message("shop.order.status.exception"));
            }
            if (!Objects.equals(order.getPayStatus(), PayStatus.NONPAYMENT)) {
                throw new QysException(MessageUtils.message("order.has.been.paid"));
            }
            //获取订单详情
            List<ShopOrderSku> skus=orderSkuService.getByOrderId(orderId);
            if (CollectionUtils.isEmpty(skus)){
                throw new QysException(MessageUtils.message("system.error.order"));
            }
            List<ShopOrderMessage> messageList = new ArrayList<>();
            long now=System.currentTimeMillis();
            for(ShopOrderSku sku:skus){
                Long shopId = sku.getShopId();
                H2ShopBase shopBase = shopBaseService.queryById(shopId);
                if (ObjectUtils.isEmpty(shopBase)||!Objects.equals(shopBase.getStatus(), ShopConstant.ShopStatus.IN_BUSINESS)){
                    throw new QysException(MessageUtils.message("shop.not.exist"));
                }
                sku.setSkuOrderId(BusinessNoUtil.get(AccountBusinessTypeEnum.USER_ORDER));
                sku.setOrderStatus(OrderStatus.UNSHIPPED);
                sku.setPayTime(LocalDateTime.now());

                if(!orderSkuService.updateById(sku)) throw new QysException(MessageUtils.message("system.error.order"));
                //加销量
                ShopGoodsSku shopGoodsSku=shopGoodsSkuService.getById(sku.getSkuId());
                ShopGoodsInfo shopGoodsInfo=shopGoodsInfoService.getById(shopGoodsSku.getShopGoodsId());
                if (shopGoodsInfo.getSalesVolume()==null){
                    shopGoodsInfo.setSalesVolume(0);
                }
                shopGoodsInfo.setSalesVolume(shopGoodsInfo.getSalesVolume()+sku.getNum());
                if(!shopGoodsInfoService.updateById(shopGoodsInfo)) throw new QysException(MessageUtils.message("system.error.order"));

                ShopOrderMessage orderMessage = new ShopOrderMessage();
                orderMessage.setName("订单消息");
                orderMessage.setBelong(ShopOrderMessageConstants.BELONG);
                orderMessage.setMessageType(ShopOrderMessageConstants.MESSAGETYPE);
                orderMessage.setMessageUserId(shopBase.getId());
                orderMessage.setMessageUserName(shopBase.getShopName());
                orderMessage.setStatus(true);
                orderMessage.setOrderId(order.getId());
                orderMessage.setCreateTime(now);
                orderMessage.setUpdateTime(now);
                messageList.add(orderMessage);
            }
            FinancePayDTO financePayDTO = new FinancePayDTO();
            financePayDTO.setUserId(order.getUserId());
            financePayDTO.setBusinessNo(order.getOrderNo());
            if (order.getTotalPostage()==null){
                order.setTotalPostage(new BigDecimal("0"));
            }
            financePayDTO.setAmountIncurred(order.getMoneys().add(order.getTotalPostage()));
            financePayDTO.setBusinessType(AccountBusinessTypeEnum.USER_ORDER);
            financeBusinessService.pay(financePayDTO);
            if(!financePayDTO.getSuccess()){
                throw new QysException(financePayDTO.getMessage());
            }
            //订单信息
            order.setPayTime(now);
            order.setUpdateTime(now);
            order.setPayType(Constants.YesNoInt.YES);
            order.setPayStatus(PayStatus.HAVE_PAYMENT);
            order.setOrderStatus(OrderStatus.UNSHIPPED);
            if(!updateById(order)) throw new QysException(MessageUtils.message("system.error.order"));
            SeckillOrder seckillOrder = seckillOrderService.getById(order.getId());
            if (ObjectUtils.isNotEmpty(seckillOrder)){
                seckillOrder.setStatus(PayStatus.HAVE_PAYMENT);
                seckillOrder.setPayTime(now);
                if(!seckillOrderService.updateById(seckillOrder)) throw new QysException(MessageUtils.message("system.error.order"));
            }
            //预算
            shopOrderSettlementService.settlementByOrder(order.getId());


            ExecutorService threadPool=null;
            try {
                applicationContext.publishEvent(new ShopEvent(ShopEventInfo.builder()
                        .shopId(System.currentTimeMillis())
                        .eventType(ShopEventTypeEnum.SHOP_ORDER.getType())
                        .paramObj(ShopOrderPojo.builder()
                                .orderId(orderId)
                                .build()
                        ).build())
                );

                //消息推送
                PushUserDeviceDTO userDeviceDTO = new PushUserDeviceDTO();
                userDeviceDTO.setUserIds(Arrays.asList(order.getUserId()));
                PushTitleDTO pushTitleDTO=new PushTitleDTO();
                pushTitleDTO.setChinese("订单");
                pushTitleDTO.setEnglish(ShopOrderMessageConstants.MESSAGETYPE);
                userDeviceDTO.setTitle(pushTitleDTO);
                PushUserDeviceContentDTO contentDTO = new PushUserDeviceContentDTO();
                contentDTO.setType(PushMessageTypeEnum.ORDER_PUSH);
                contentDTO.setData(ShopOrderMessageConstants.USERORDER);
                userDeviceDTO.setContent(contentDTO);
                Result pushFlag = pushUserDeviceService.pushUserDevice(userDeviceDTO);
                if (!messageService.saveBatch(messageList))throw new QysException(MessageUtils.message("system.error.order"));

                threadPool = Executors.newFixedThreadPool(2);
                //销售达到要求推送消息
                threadPool.execute(() -> this.sendSalesQuantity(skus));
                //更新带货心愿
                List<ShopOrderSku> shopOrderSkus = skus.stream().filter(e -> e.getTaskId() != null).toList();
                threadPool.execute(() -> this.updateTheWishToBringGoods(shopOrderSkus));

            }catch (Exception e){
                log.error("处理订单推送和带货星愿错误，"+e);
            }finally {
                if (threadPool!=null) {
                    //关闭线程池
                    threadPool.shutdown();
                }
            }
            return R.ok();
        }
    }

    private void updateTheWishToBringGoods(List<ShopOrderSku> shopOrderSku){
        try {
            //如果订单涉及直播间带货心愿，更新数据
            if(!CollectionUtils.isEmpty(shopOrderSku)){

                Long sessionId = shopOrderSku.get(0).getTaskId();
                String livesRoomNum = anchorServer.getRoomInfoByLivesSessionId(sessionId);

                //推送商品购买人，同时获取购的商品编号，以及数量
                Map<Long, List<ShopOrderSku>> sukList = shopOrderSku.stream().collect(Collectors.groupingBy(ShopOrderSku::getSkuId));
                sukList.forEach((k,v) -> {
                    //购买总数
                    int sum = v.stream().mapToInt(ShopOrderSku::getNum).sum();

                    //获取商品在直播间的编号
                    Map<String, Integer> cacheMap = redisCache.getCacheMap("live:goodsNumber:" + sessionId);
                    Integer number = null;
                    if (!CollectionUtils.isEmpty(cacheMap)) {
                        ShopGoodsSku goodsSku = skuService.getById(k);
                        number = cacheMap.get(String.valueOf(goodsSku.getShopGoodsId()));
                    }

                    //用户购买信息，格式：购买者_商品编号_数量
                    H2AppUser appUser = userMapper.selectById(shopOrderSku.get(0).getUserId());
                    String latestBuyerInfo = Optional.ofNullable(appUser.getNickName()).orElse(StringUtils.EMPTY) + "_" + number + "_" + sum;

                    HashMap<String, String> buyerMap = Maps.newHashMap();
                    buyerMap.put("latestBuyer", latestBuyerInfo);
                    tencentCloudIm.modifyGroupInfo(livesRoomNum, buyerMap, true);
                });

                log.info("判断是否有带货心愿");
                //是否存在带货心愿,格式为 goodsId:total:finish
                String cacheObject = redisCache.getCacheObject("live:goodsWish:" + sessionId);
                if(StringUtils.isNotEmpty(cacheObject)){
                    log.info("匹配到带货心愿，{}", cacheObject);
                    int total = 0;
                    for (ShopOrderSku orderSku : shopOrderSku) {
                        ShopGoodsSku goodsSku = skuService.getById(orderSku.getSkuId());
                        if(String.valueOf(goodsSku.getShopGoodsId()).equals(cacheObject.split(":")[0])){
                            total += orderSku.getNum();
                        }
                    }
                    if(total > 0){
                        //更新直播间心愿
                        HashMap<String, String> map = Maps.newHashMap();
                        int newFinish = total + Integer.parseInt(cacheObject.split(":")[2]);
                        map.put("wishFinish", String.valueOf(newFinish));
                        Boolean ok = tencentCloudIm.modifyGroupInfo(livesRoomNum, map, true);
                        log.info("更新带货心愿成功，{}", JSONObject.toJSONString(map));
                        if(ok){
                            //更新缓存
                            redisCache.setCacheObject("live:goodsWish:" + sessionId, cacheObject.split(":")[0] + ":" + cacheObject.split(":")[1] + ":" + newFinish, 60L, TimeUnit.MINUTES);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("更新带货心愿异常", e);
        }
    }

    /**
     * 销售达到要求推送消息
     * @param skus
     */
    public void sendSalesQuantity(List<ShopOrderSku> skus){
        List<PushAllDeviceDTO> pushAllDeviceDTOS=new ArrayList<>();
        for(ShopOrderSku sku:skus){
            Long shopId = sku.getShopId();
            H2ShopBase shopBase = shopBaseService.queryById(shopId);
            String day=DateUtils.parseDateNow();
            //店主推送信息
            Integer shopCount=redisCache.getCacheObject("shop:"+shopBase.getId()+":skuNum:"+day);
            if (null == shopCount){
                shopCount=0;
            }
            int newShopCount = shopCount.intValue()+sku.getNum().intValue();
            if ((10000 > shopCount.intValue() && newShopCount>= 10000 ) || (100000 > shopCount.intValue() && newShopCount>= 100000)){
                H2AppUser h2AppUser=userMapper.selectById(Long.valueOf(shopBase.getUserId()));
                PushAllDeviceDTO pushAllDeviceDTO=new PushAllDeviceDTO();
                PushTitleDTO pushTitleDTO=new PushTitleDTO();
                pushTitleDTO.setChinese(h2AppUser.getNickName()+"店主当日销量达成"+newShopCount+"单子");
                pushTitleDTO.setEnglish(h2AppUser.getNickName()+"'s store owner sold "+newShopCount+" orders on the same day");
                pushAllDeviceDTO.setTitle(pushTitleDTO);
                PushUserDeviceContentDTO pushUserDeviceContentDTO=new PushUserDeviceContentDTO();
                pushUserDeviceContentDTO.setType(PushMessageTypeEnum.NOTICE_ALL);
                JSONObject json = new JSONObject();
                json.put("chinese",h2AppUser.getNickName()+"店主当日销量达成"+newShopCount+"单子");
                json.put("english",h2AppUser.getNickName()+"'s store owner sold "+newShopCount+" orders on the same day");
                pushUserDeviceContentDTO.setData(json.toString());
                pushAllDeviceDTO.setContent(pushUserDeviceContentDTO);
                pushAllDeviceDTOS.add(pushAllDeviceDTO);
            }
            redisCache.setCacheObject("shop:"+shopBase.getId()+":skuNum:"+day,newShopCount,Long.valueOf(24), TimeUnit.HOURS);
            //主播推送信息
            if (null==sku.getAnchorId()){
                continue;
            }
            Integer anchorCount=redisCache.getCacheObject("anchor:"+sku.getAnchorId()+":skuNum:"+day);
            if (null == anchorCount){
                anchorCount=0;
            }
            int newAnchorCount=anchorCount.intValue()+sku.getNum().intValue();
            if ((10000 > anchorCount.intValue() && newAnchorCount>= 10000 ) || (100000 > anchorCount.intValue() && newAnchorCount>= 100000)){
                Map<String,Object> map=anchorServer.getAnchor(sku.getAnchorId());
                PushAllDeviceDTO pushAllDeviceDTO=new PushAllDeviceDTO();
                PushTitleDTO pushTitleDTO=new PushTitleDTO();
                pushTitleDTO.setChinese(map.get("name")+"主播当日销量达成"+newAnchorCount+"单子");
                pushTitleDTO.setEnglish(map.get("name")+"'s anchor achieved "+newAnchorCount+" sales on the same day");
                pushAllDeviceDTO.setTitle(pushTitleDTO);
                PushUserDeviceContentDTO pushUserDeviceContentDTO=new PushUserDeviceContentDTO();
                pushUserDeviceContentDTO.setType(PushMessageTypeEnum.NOTICE_ALL);
                JSONObject json = new JSONObject();
                json.put("chinese",map.get("name")+"主播当日销量达成"+newAnchorCount+"单子");
                json.put("english",map.get("name")+"'s anchor achieved "+newAnchorCount+" sales on the same day");
                pushUserDeviceContentDTO.setData(json.toString());
                pushAllDeviceDTO.setContent(pushUserDeviceContentDTO);
                pushAllDeviceDTOS.add(pushAllDeviceDTO);
            }
            redisCache.setCacheObject("anchor:"+sku.getAnchorId()+":skuNum:"+day,newAnchorCount,Long.valueOf(24), TimeUnit.HOURS);
        }
        if (CollectionUtil.isNotEmpty(pushAllDeviceDTOS)){
            for (PushAllDeviceDTO pushAllDeviceDTO:pushAllDeviceDTOS){
                pushUserDeviceService.pushAllUserDevice(pushAllDeviceDTO);
            }
        }
    }
}
